﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using System.Collections;
using System.Data;
using System.ComponentModel;
using StockAdjust;
using MyException;

namespace PresentationLayer
{
    public partial class IssueStockAdjustment : System.Web.UI.Page
    {
        IssueStockAdjustmentVoucherControl control;

        int adjustQuantity;
        string categoryName;
        int categoryId;
        string itemName;
        string itemCode;
        string supplierName;
        string supplierId;
        string reason;
        string adjustCondition;
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            control = new IssueStockAdjustmentVoucherControl();

            // Fake user
            string username = "Clerk1";
            user = control.GetUserByUsername(username);

            if (!IsPostBack)
            {
                // Populate 3 dropdownlists
                PopulateCategory();
                PopulateItemName();
                PopulateSupplierName();

                // Populate GridView
                DisplayGridView();
            }
            else
            {
                lblError.Text = "";
                lblError1.Text = "";
                lblErrorSubmit.Text = "";
                lblSuccess.Text = "";
            }
        }

        protected void ddlCategory_TextChanged(object sender, EventArgs e)
        {
            // Re-populate 2 dropdownlists
            PopulateItemName();
            PopulateSupplierName();
        }

        protected void ddlItemName_TextChanged(object sender, EventArgs e)
        {
            // Re-populate 1 dropdownlist
            PopulateSupplierName();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Re-set fields back to default
            ResetFields();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            // Read input from form fields
            adjustQuantity = 0;
            categoryName = ddlCategory.SelectedItem.ToString();
            categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            itemName = ddlItemName.SelectedItem.ToString();
            itemCode = ddlItemName.SelectedValue;
            supplierName = ddlSupplierName.SelectedItem.ToString();
            supplierId = ddlSupplierName.SelectedValue;
            reason = txtReason.Text.Trim();
            adjustCondition = rbtnlAdjustDetail.SelectedValue;

            Stationery stationery = control.GetStationeryByItemCode(itemCode);

            try
            {
                adjustQuantity = Convert.ToInt32(txtAdjustDetail.Text.Trim());

                if (adjustCondition.Equals("Current quantity in stock"))
                {
                    if (adjustQuantity < 0)
                    {
                        throw new CurrentStockException();
                    }
                }
                else
                {

                    if (adjustQuantity == 0 || adjustQuantity < (-1 * stationery.AvailableQty))
                    {
                        throw new AdjustQuantityException();
                    }
                }

                // Count HttpCookies
                int count = (int)CountAndLastDigit()[0];
                int lastDigit = (int)CountAndLastDigit()[1];
                int exist = (int)CountAndLastDigit()[2];

                // Add HttpCookie and display GridView and Submit button
                if (reason != "" && adjustQuantity != 0)
                {
                    if (exist == 1)
                    {
                        lblError.Text = "* " + itemName + " supplied by " + supplierName + " has already been added into the list.";
                    }
                    else
                    {
                        // Store in HttpCookie
                        HttpCookie newCookie = new HttpCookie("adjust" + (lastDigit + 1));
                        newCookie.Values.Add("userId", user.UserID.ToString());
                        newCookie.Values.Add("categoryName", categoryName);
                        newCookie.Values.Add("categoryId", categoryId.ToString());
                        newCookie.Values.Add("itemName", itemName);
                        newCookie.Values.Add("itemCode", itemCode);
                        newCookie.Values.Add("supplierName", supplierName);
                        newCookie.Values.Add("supplierId", supplierId);
                        newCookie.Values.Add("reason", reason);
                        newCookie.Values.Add("adjustCondition", adjustCondition);
                        newCookie.Values.Add("adjustQuantity", adjustQuantity.ToString());
                        Response.Cookies.Add(newCookie);

                        count++;

                        // Reset fields back to default
                        ResetFields();

                        // Display GrideView and Submit button     
                        if (count >= 1)
                        {
                            // bind data to gridview
                            PopulateGridView();
                            gvAdjustDetail.Visible = true;
                            btnSubmit.Visible = true;
                        }
                        else
                        {
                            gvAdjustDetail.Visible = false;
                            btnSubmit.Visible = false;
                        }
                    }
                }
            }
            catch (FormatException ex)
            {
                // Continue with form validation
            }
            catch (CurrentStockException ex)
            {
                lblError.Text = "* Quantity must be more than or equal to 0";
                lblError1.Text = "*";
            }
            catch (AdjustQuantityException ex)
            {
                lblError.Text = "* Quantity cannot be less than -" + stationery.AvailableQty + " and cannot be 0";
                lblError1.Text = "*";
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool result = true;
            for (int i = 0; i < gvAdjustDetail.Rows.Count; i++)
            {
                if (gvAdjustDetail.Rows[i].RowState == DataControlRowState.Edit)
                {
                    result = false;
                }
            }
            if (result == false)
            {
                lblErrorSubmit.Text = "* Please update or cancel the changes before proceeding";

            }
            else
            {
                // Obtain values from cookies
                List<StockAdjustment> list = GenerateStockAdjustmentList();

                // Save to database
                control.SaveAdjustmentVoucher(user, list);

                // Delete info saved in HttpSession
                HttpCookieCollection myCookieCollection = Request.Cookies;

                for (int j = 0; j < myCookieCollection.Count; j++)
                {
                    HttpCookie myCookie = myCookieCollection[j];
                    if (myCookie.Name.StartsWith("adjust"))
                    {
                        Response.Cookies[myCookie.Name].Expires = DateTime.Now.AddDays(-1);
                    }
                }

                // Reset page and display GridView
                myCookieCollection.Clear();
                ResetFields();
                DisplayGridView();

                lblSuccess.Text = "Stock Adjustment Voucher has been submitted successfully";
            }
        }

        #region Populate Control Information
        private void PopulateCategory()
        {
            ddlCategory.DataSource = control.DisplayAllCategory();
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
        }

        private void PopulateItemName()
        {
            int categoryId = Convert.ToInt32(ddlCategory.SelectedValue.ToString());
            ddlItemName.DataSource = control.DisplayStationeryByCategoryId(categoryId);
            ddlItemName.DataTextField = "ItemName";
            ddlItemName.DataValueField = "ItemCode";
            ddlItemName.DataBind();
        }

        private void PopulateSupplierName()
        {
            string itemCode = ddlItemName.SelectedValue.ToString();
            ddlSupplierName.DataSource = control.DisplaySupplierByItemCode(itemCode);
            ddlSupplierName.DataTextField = "SupplierName";
            ddlSupplierName.DataValueField = "SupplierID";
            ddlSupplierName.DataBind();
        }

        private List<StockAdjustment> GenerateStockAdjustmentList()
        {
            HttpCookieCollection myCookieCollection = Request.Cookies;
            List<StockAdjustment> list = new List<StockAdjustment>();
            for (int i = 0; i < myCookieCollection.Count; i++)
            {
                StockAdjustment stock = new StockAdjustment();
                HttpCookie myCookie = myCookieCollection[i];
                if (user.UserID.ToString().Equals(myCookie.Values.Get("userId")))
                {
                    if (myCookie.Name.StartsWith("adjust"))
                    {
                        stock.UserId = Convert.ToInt32(myCookie.Values.Get("userId"));
                        stock.ItemCode = myCookie.Values.Get("itemCode");
                        stock.ItemName = myCookie.Values.Get("itemName");
                        stock.CategoryId = Convert.ToInt32(myCookie.Values.Get("categoryId"));
                        stock.CategoryName = myCookie.Values.Get("categoryName");
                        stock.SupplierId = myCookie.Values.Get("supplierId");
                        stock.SupplierName = myCookie.Values.Get("supplierName");
                        stock.AdjustQuantity = Convert.ToInt32(myCookie.Values.Get("adjustQuantity"));
                        stock.AdjustCondition = myCookie.Values.Get("adjustCondition");
                        stock.Reason = myCookie.Values.Get("reason");

                        list.Add(stock);
                    }
                }
            }
            return list;
        }

        public void PopulateGridView()
        {
            List<StockAdjustment> list = GenerateStockAdjustmentList();

            list = list.OrderBy(x => x.CategoryName).ThenBy(x => x.ItemCode).ThenBy(x => x.SupplierName).ToList();
            gvAdjustDetail.DataSource = list;
            gvAdjustDetail.DataBind();
        }

        public void DisplayGridView()
        {
            if ((int)CountAndLastDigit()[0] >= 1)
            {
                PopulateGridView();
                gvAdjustDetail.Visible = true;
                btnSubmit.Visible = true;
            }
            else
            {
                gvAdjustDetail.Visible = false;
                btnSubmit.Visible = false;
            }
        }
        #endregion

        #region Track Cookie
        private ArrayList CountAndLastDigit()
        {
            ArrayList temp = new ArrayList();
            int count = 0;
            int lastDigit = 0;
            int exist = 0;
            string cookieName = "";
            temp.Add(count);
            temp.Add(lastDigit);
            temp.Add(exist);
            temp.Add(cookieName);
            itemCode = ddlItemName.SelectedValue;
            supplierId = ddlSupplierName.SelectedValue;
            HttpCookieCollection myCookieCollection = Request.Cookies;

            for (int i = 0; i < myCookieCollection.Count; i++)
            {
                HttpCookie myCookie = myCookieCollection[i];
                if (user.UserID.ToString().Equals(myCookie.Values.Get("userId")))
                {
                    if (myCookie.Name.StartsWith("adjust"))
                    {
                        if (myCookie.Values.Get("itemCode").Equals(itemCode) && myCookie.Values.Get("supplierId").Equals(supplierId))
                        {
                            exist = 1;
                            cookieName = myCookie.Name;
                        }
                        count++;
                        lastDigit = Convert.ToInt32(myCookie.Name.Replace("adjust", ""));
                    }
                }
            }

            temp[0] = count;
            temp[1] = lastDigit;
            temp[2] = exist;
            temp[3] = cookieName;

            return temp;
        }
        #endregion

        #region Reset Fields
        private void ResetFields()
        {
            PopulateCategory();
            PopulateItemName();
            PopulateSupplierName();
            txtReason.Text = "";
            txtAdjustDetail.Text = "";
        }
        #endregion

        #region GridView Functions
        protected void gvAdjustDetail_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvAdjustDetail.EditIndex = e.NewEditIndex;
            PopulateGridView();
        }

        protected void gvAdjustDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvAdjustDetail.EditIndex = -1;
            PopulateGridView();
        }

        protected void gvAdjustDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // Update cookie
            Label itemCodeGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("lblItemCode") as Label;
            Label supplierNameGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("lblSupplierName") as Label;
            TextBox adjQuantityGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("txtAdjQuantity") as TextBox;
            int adjQty = Convert.ToInt32(adjQuantityGV.Text.Trim());
            HttpCookieCollection myCookieCollection = Request.Cookies;
            HttpCookie myCookie = null;
            Stationery stationery = null;
            try
            {
                for (int i = 0; i < myCookieCollection.Count; i++)
                {
                    myCookie = myCookieCollection[i];
                    if (user.UserID.ToString().Equals(myCookie.Values.Get("userId")))
                    {
                        if (myCookie.Name.StartsWith("adjust"))
                        {
                            stationery = control.GetStationeryByItemCode(myCookie.Values.Get("itemCode"));
                            if (myCookie.Values.Get("itemCode").Equals(itemCodeGV.Text) && myCookie.Values.Get("supplierName").Equals(supplierNameGV.Text))
                            {
                                if (myCookie.Values.Get("adjustCondition").Equals("Current quantity in stock"))
                                {
                                    if (adjQty < 0)
                                    {
                                        throw new CurrentStockException();
                                    }
                                }
                                else
                                {
                                    if (adjQty == 0 || adjQty < (-1 * stationery.AvailableQty))
                                    {
                                        throw new AdjustQuantityException();
                                    }
                                }
                                myCookie.Values.Set("adjustQuantity", adjQty.ToString());
                                Response.SetCookie(myCookie);
                                myCookieCollection.Remove(myCookie.Name);
                                HttpCookie tempCookie = myCookie;
                                myCookieCollection.Add(tempCookie);
                                break;
                            }
                        }
                    }
                }
                gvAdjustDetail.EditIndex = -1;
                PopulateGridView();
            }
            catch (CurrentStockException ex)
            {
                lblErrorSubmit.Text = "* Quantity must be more than or equal to 0";
            }
            catch (AdjustQuantityException ex)
            {
                lblErrorSubmit.Text = "Quantity cannot be less than -" + stationery.AvailableQty + " and cannot be 0";
            }
        }

        protected void gvAdjustDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // delete cookie
            Label itemCodeGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("lblItemCode") as Label;
            Label supplierNameGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("lblSupplierName") as Label;
            TextBox adjQuantityGV = gvAdjustDetail.Rows[e.RowIndex].FindControl("txtAdjQuantity") as TextBox;
            HttpCookieCollection myCookieCollection = Request.Cookies;
            for (int i = 0; i < myCookieCollection.Count; i++)
            {
                HttpCookie myCookie = myCookieCollection[i];
                if (user.UserID.ToString().Equals(myCookie.Values.Get("userId")))
                {
                    if (myCookie.Name.StartsWith("adjust"))
                    {
                        if (myCookie.Values.Get("itemCode").Equals(itemCodeGV.Text) && myCookie.Values.Get("supplierName").Equals(supplierNameGV.Text))
                        {
                            Response.Cookies[myCookie.Name].Expires = DateTime.Now.AddDays(-1);
                            myCookieCollection.Remove(myCookie.Name);
                        }
                    }
                }
            }
            DisplayGridView();
        }
        #endregion

    }
}